package controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import util.VersionException;
import domain.Address;
import domain.Contact;
import domain.ContactGroup;
import domain.Entreprise;
import domain.PhoneNumber;
import domain.factory.POJOFactory;
import domain.itf.IDAOContact;
import domain.itf.IDAOContactGroup;

/**
 * Controller class for modify a member
 */
@Controller
@RequestMapping("/UpdateContact")
public class UpdateContactController {

	@Autowired
	ServletContext servletContext;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("updateContact");
		String memberIdString = request.getParameter("memberId");
		try {
			int memberId = Integer.parseInt(memberIdString);

			// get the IDAOContact with spring
			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
			IDAOContact daoContact =(IDAOContact) context.getBean("DAOContact");
			IDAOContactGroup daoContactGroup =(IDAOContactGroup) context.getBean("DAOContactGroup");

			//Load contact by this id
			Contact contact = daoContact.getById(memberId);
			
			if(contact == null)
				return new ModelAndView("main").addObject("messageError", "Impossible to get this member.");
			
			if(contact instanceof Entreprise)
				view.addObject("numEntreprise",((Entreprise) contact).getNumSiret());

			view.addObject("contact", contact);


			//Group selected
			Set<ContactGroup> groupsSelected = contact.getBooks();
			if (groupsSelected.isEmpty())
				view.addObject("groupsSelected", null);
			else
				view.addObject("groupsSelected", groupsSelected);
			

			//Load groups
			List<ContactGroup> groups = daoContactGroup.getAllGroups();
			//Deleting extra group
			for (ContactGroup contactGroup : groupsSelected) {
				if(groups.contains(contactGroup))
					groups.remove(contactGroup);
			}
			
			if (groups.isEmpty())
				view.addObject("groups", null);
			else
				view.addObject("groups", groups);


			return view;

		} catch (NumberFormatException e) {
			ModelAndView view2 = new ModelAndView("main");
			view2.addObject("messageError", "Impossible to get the member.");
			return view2;
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView doPost(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("main");

		//get the contact
		String idContact = request.getParameter("idContact");
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String email = request.getParameter("emailC");
		String versionContact = request.getParameter("versionContact");
		String numSiretString = request.getParameter("siret");

		//get Address
		String idAddress = request.getParameter("idAddress");
		String versionAddr = request.getParameter("versionContact");
		String zipCode = request.getParameter("zip");
		String street = request.getParameter("street");
		String city = request.getParameter("city");
		String country = request.getParameter("country");

		//get list of phone 
		String[] phones = request.getParameterValues("phoneNumbers");
		String[] kinds = request.getParameterValues("kindTypes");
		String[] idPhones = request.getParameterValues("idPhone");
		String[] versionPhones = request.getParameterValues("versionPhone");

		//get the selected list of group 
		String[] groupsStrings = request.getParameterValues("groups");

		try {
			//Infos contact
			int memberId = Integer.parseInt(idContact);
			long version = Long.parseLong(versionContact);

			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);

			/**
			 * Address
			 */
			//Info Address
			int idAddressInt = Integer.parseInt(idAddress);
			long versionAddress = Long.parseLong(versionAddr);

			// MAJ of Address
			Address address = POJOFactory.instance.newAddress(street, city, zipCode, country);
			address.setId(idAddressInt);
			address.setVersion(versionAddress);
			
			/**
			 *  Phone
			 */
			//Info Address
			Set<PhoneNumber> setPhoneNumber = new HashSet<PhoneNumber>();
			if(phones != null)
			{
				int idPhone;
				long versionPhone;
				String kindPhone, phoneNumber;
				PhoneNumber phone;
				
				for (int i = 0; i < phones.length; i++) {
					kindPhone = kinds[i];
					phoneNumber = phones[i];
					//We update
					if(idPhones != null && idPhones.length > i)
					{
						idPhone = Integer.parseInt(idPhones[i]);
						versionPhone = Long.parseLong(versionPhones[i]);
						phone = POJOFactory.instance.newPhoneNumber(kindPhone, phoneNumber, null);
						phone.setId(idPhone);
						phone.setVersion(versionPhone+1);
					}
					else
						phone = POJOFactory.instance.newPhoneNumber(kindPhone, phoneNumber, null);

					setPhoneNumber.add(phone);
				}
			}
			
			/***
			 * Group
			 */
			// get the IDAOContact with spring
			IDAOContactGroup daoContactGroup =(IDAOContactGroup) context.getBean("DAOContactGroup");
			Set<ContactGroup> setContactGroup = new HashSet<ContactGroup>();
			if(groupsStrings != null)
			{
				for (String groupId : groupsStrings) {
					setContactGroup.add(daoContactGroup.getById(Integer.parseInt(groupId)));
				}
			}

			/***
			 * Contact
			 */
			// get the IDAOContact with spring
			IDAOContact daoContact =(IDAOContact) context.getBean("DAOContact");

			// MAJ of contact
			Contact contact = null;
			
			if(numSiretString != null)
				contact = daoContact.updateContact(memberId, version, firstName, lastName, email, address, setContactGroup, setPhoneNumber, Integer.parseInt(numSiretString));
			else
				contact = daoContact.updateContact(memberId, version, firstName, lastName, email, address, setContactGroup, setPhoneNumber, null);

			if (contact != null)
				view.addObject("messageInfo", "You have sucessful modify the member informations.");
			else 
				view.addObject("messageError", "Impossible to modify the member informations.");

		} catch (NumberFormatException e) {
			view.addObject("messageError", "Impossible to modify the member.");
		} catch (VersionException e) {
			view.addObject("messageError", e.getMessage());
		}

		return view;
	}
}
